
import  server  from './axios'
import { ElMessage } from 'element-plus'
let {myAxios} = server();


//把bolb文件进行分片处理 
function blobToBase64Chunks(blob, chunkSize = 1024 * 1024) {
    return new Promise(async (r,j) =>{
        const totalChunks = Math.ceil(blob.size / chunkSize);
        let arr = [];
        const promises = [];
        for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize;
            const end = Math.min((i + 1) * chunkSize, blob.size);
            const chunk = blob.slice(start, end);
            const base64Chunk = await blobToBase64(chunk);
            arr.push(base64Chunk);
            if(i == totalChunks-1){
                r(arr);
            }
        }
    })
}
// 合并 Blob 文件
function mergeBlob(chunks) {
    const blobArray = chunks.map(chunk => chunk.arrayBuffer());
    return new Blob(blobArray, { type: chunks[0].type });
}
//把bolb  对象转换成  base64
function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        resolve(reader.result.split(',')[1]);
      };
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
}

//把base64文件进行下载
function base64ToByteArray(base64) {
    const binary = window.atob(base64.replace(/\s/g, ''));
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
}
function base64ToBlob(base64, type = 'application/octet-stream') {
    const bytes = base64ToByteArray(base64);
    return new Blob([bytes], { type });
}
function saveBase64AsFile(base64, fileName) {
    const blob = base64ToBlob(base64);
    const link = document.createElement('a');
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    link.click();
    URL.revokeObjectURL(link.href);
}

class audiow {
    //获取音频文件
    getfileData(id){
        return new Promise(async (r,j) =>{
            let file = document.getElementById(id);
            let dile = file.files[0];
            // let url = await blobToBase64(dile);
            let arr = await blobToBase64Chunks(dile);
            r(arr);
        })
    }
    getGUid(url,IMGGUID){
        return new Promise((r,j) =>{
            let par = {
                RelateType:319,
                RelateID:0,
                PicData:url,
                IMGGUID:IMGGUID || '',
                ExtName:'pptx'
            }
            myAxios('PublicService.UploadPicForBlob',par).then(res =>{
                r(res.PicGUID)
            })
        })
    }
}
let audioUp = new audiow();
audioUp.__proto__.getAudioGUid = async (id) =>{
    let formData = await audioUp.getfileData(id);
    return formData;
}

export default function(id){
    return audioUp
}